package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import util.ConfigManager;

public class BaseDao {
	private Connection connection=null;
	private PreparedStatement pstm=null;
	private ResultSet rs=null;
	// 获取数据库连接
	public boolean getConnection(){
	try {
		String driver=ConfigManager.getInstance().getString("jdbc.driver.class");
		String url=ConfigManager.getInstance().getString("jdbc.connection.url");
		String username=ConfigManager.getInstance().getString("jdbc.connection.username");
		String password=ConfigManager.getInstance().getString("jdbc.connection.password");
		Class.forName(driver);
		//获得数据库连接
	  connection=DriverManager.getConnection(url,username,password);
		return true;
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return false;
	}
}		
	// 查询
	public ResultSet executeSQL(String sql,Object[] params){
		try {
			if(this.getConnection()){
				pstm=connection.prepareStatement(sql);
				for(int i=0;i<params.length;i++){
					pstm.setObject(i+1,params[i]);
				}
				this.rs= pstm.executeQuery();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
	//增删改
	public int executeUpdate(String sql,Object[]params){
		int updateRows=0;
		if(this.getConnection()){
			try {
				pstm=connection.prepareStatement(sql);
				//填充占位符
				for(int i=0;i<params.length;i++){
					pstm.setObject(i+1, params[i]);
				}
				updateRows=pstm.executeUpdate();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return updateRows;
	}
	public boolean closeResoutce(){
		try {
			if(rs!=null){
				rs.close();
			}
			if(pstm!=null){
				pstm.close();
			}
			if(connection!=null){
				connection.close();
			}
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
}
